package handler

import (
	"github.com/gin-gonic/gin"
	"main/pkg"
	"strconv"
	"time"

	"main/api/request"
	"main/internal/dao"
	"main/internal/model"
	"net/http"
)

func UserRegister(c *gin.Context) {
	//接参
	var req request.RegisterReq

	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证错误",
			"data": err.Error(),
		})
	}

	//业务逻辑
	if req.Password != req.Confirm {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "两次密码不一致",
			"data": false,
		})
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	}

	//返回
	dao.AddFields(&user)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": user.Id,
	})
}

func UserLogin(c *gin.Context) {
	//接参
	var req request.LoginReq

	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证错误",
			"data": err.Error(),
		})
	}

	//业务逻辑

	user = model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}

	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)

	//返回
	if user.Id == 0 && user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登录失败,账号密码错误",
			"data": nil,
		})
	}

	token := pkg.CreateJwtToken(strconv.FormatInt(user.Id, 10), 24*time.Hour, "2302a")

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"data": token,
	})
	pkg.AuthJwtToken(token, "2302a")
}
